import time
import json
import os
import sys
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.utils.logger import Logger
from collections import deque
from threading import Lock

# 创建性能监控日志记录器
logger = Logger("PerformanceMonitor")

class PerformanceMonitor:
    """性能监控类，用于记录和分析AI响应时间"""
    
    def __init__(self, max_records=1000, log_file="performance.log"):
        """
        初始化性能监控器
        
        Args:
            max_records (int): 最大记录数，防止内存占用过多
            log_file (str): 性能日志文件路径
        """
        self.max_records = max_records
        self.log_file = log_file
        self.records = deque(maxlen=max_records)
        self.lock = Lock()
        
        # 确保日志目录存在
        log_dir = os.path.dirname(log_file) if os.path.dirname(log_file) else "."
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir)
    
    def start_timing(self):
        """
        开始计时
        
        Returns:
            float: 开始时间戳
        """
        return time.time()
    
    def end_timing(self, start_time, query="", response="", error=None):
        """
        结束计时并记录性能数据
        
        Args:
            start_time (float): 开始时间戳
            query (str): 用户查询
            response (str): AI响应
            error (str): 错误信息（如果有）
        """
        end_time = time.time()
        duration = end_time - start_time
        
        # 创建性能记录
        record = {
            "timestamp": datetime.now().isoformat(),
            "query": query[:100] + "..." if len(query) > 100 else query,  # 限制查询长度
            "response": response[:200] + "..." if len(response) > 200 else response,  # 限制响应长度并记录响应内容
            "response_length": len(response),
            "duration": duration,
            "error": error
        }
        
        # 线程安全地添加记录
        with self.lock:
            self.records.append(record)
            
            # 写入日志文件
            try:
                with open(self.log_file, "a", encoding="utf-8") as f:
                    f.write(json.dumps(record, ensure_ascii=False) + "\n")
            except Exception as e:
                logger.error(f"写入性能日志文件失败: {e}")
        
        # 记录到标准日志
        if error:
            logger.error(f"处理耗时: {duration:.3f}s, 查询: {record['query']}, 错误: {error}")
        else:
            logger.info(f"这个查询: {record['query']},处理耗时: {duration:.3f}s, 响应长度: {record['response_length']}")
    
    def get_stats(self):
        """
        获取性能统计信息
        
        Returns:
            dict: 包含统计信息的字典
        """
        # 添加调试日志
        logger.info(f"获取性能统计信息，当前记录数: {len(self.records)}")
        
        if not self.records:
            return {"message": "暂无性能数据"}
        
        durations = [record["duration"] for record in self.records if record["error"] is None]
        error_count = sum(1 for record in self.records if record["error"] is not None)
        
        if not durations:
            return {
                "total_requests": len(self.records),
                "error_requests": error_count,
                "success_rate": 0,
                "message": "所有请求都出现错误"
            }
        
        return {
            "total_requests": len(self.records),
            "error_requests": error_count,
            "success_rate": (len(durations) / len(self.records)) * 100,
            "avg_duration": sum(durations) / len(durations),
            "min_duration": min(durations),
            "max_duration": max(durations),
            "last_10_requests": list(self.records)[-10:] if len(self.records) >= 10 else list(self.records)
        }
    
    def clear_records(self):
        """清空性能记录"""
        with self.lock:
            count_before = len(self.records)
            self.records.clear()
            logger.info(f"性能记录已清空，清空前记录数: {count_before}")

# 创建全局性能监控实例
performance_monitor = PerformanceMonitor()

# 便捷函数
def start_timing():
    """开始计时"""
    return performance_monitor.start_timing()

def end_timing(start_time, query="", response="", error=None):
    """结束计时并记录性能数据"""
    performance_monitor.end_timing(start_time, query, response, error)

def get_performance_stats():
    """获取性能统计信息"""
    return performance_monitor.get_stats()

def clear_performance_records():
    """清空性能记录"""
    performance_monitor.clear_records()